//
//  VoiceView.swift
//  TLCLockDemo
//
//  Created by run on 2024/7/24.
//

import SwiftUI
import TLCLock

struct VoiceView: View {


    let device: LockDevice
    @State var volume: String = "100"

    var body: some View {
        
        VStack {
            YxrInputView("音量", placeholderText: "0~254", text: $volume)
                .padding(.vertical, 10)
            YxrActionView(
                data: [
                    (0, "中文"),
                    (1, "英文"),
                ], column: 3,
                itemBuilder: { value in
                    YXRActionItem(text: value.1) {
                        switch value.0 {
                        case 0: sound(type: .chinese)
                        case 1: sound(type: .english)
                        default:
                            print("未实现的方法")
                        }
                    }
                }
            )
            .padding(.horizontal, 10)
            
            LogView()
        }
        .yxrNavigationTitle("声音设置")
    }

    func sound(type: LanguageType) {
        if volume.isEmpty {
            showToast("请输入音量大小")
            return
        }

        let v = volume.trimmingCharacters(in: .whitespaces)
        guard let volumeValue = Int(v) else {
            showToast("请输入正确的数字")
            return
        }

        if volumeValue > 254 || volumeValue < 0 {
            showToast("时长范围0~254")
            return
        }

        guard let lockKey = Server.getSecret(device.macAddress) else {
            showToast("没有lockKey")
            return
        }

        lockTask(desc: "声音设置") {
            await device.sound(language: type, volume: UInt8(volumeValue), lockKey: lockKey, trackId: Server.testTrackId)
        }
    }
}
